package com.uam.core.lk.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author 祝展
 * @version 1.0
 * @description
 * @Date 2019/11/7 19:29
 **/
@WebFilter(urlPatterns = "/*")
@Order(2)
public class HttpTraceFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(HttpTraceFilter.class);

    @Override
    public void init(FilterConfig filterConfig) {
        logger.info("Init Trace filter...");
        // ...
        logger.info("Init Trace filter success!");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String traceId = httpRequest.getHeader("TraceId");
        if(traceId==null || traceId.length()==0 ){
            traceId = UUIDUtil.uuidCharUpper();
        }else{
            logger.info("TraceFilter 从上游传递了TraceId:" + traceId);
        }
        MDC.put("TraceId", traceId);
        try {
            //将请求和应答交给下一个处理器处理
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            logger.error("TraceFilter error", e);
            throw e;
        } finally {
            MDC.remove("TraceId");
        }
    }

    @Override
    public void destroy() {
        logger.info("Destroy Trace filter success!");
    }
}
